﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using ReflectionStudio.Core;
using ReflectionStudio.Core.Database;
using ReflectionStudio.Core.Events;
using ReflectionStudio.Core.FTPClient;
namespace WPFExcelReport
{
    public partial class GreigeMasterReport : BaseReport
    {
        string WANEUB = "", WANEUD = "";
        string WAAENB = "", WAAEND = "";
        BaseFunction m_GM = new BaseFunction();
        #region Variable
        public FTPClient ftpClient;
        byte[] b;
        string MultiRowTable = "WASTGA;WASTPASS;BASTGA;GASTGA;WTLEIST;BASTKE;";
        int WarpBeamEnds11 = 0;
        int TotalEnds = 0;
        int TotalSelvage = 0;
        string ArticleNum;
        string ArticleVar;
        string ArticleColor;
        string ArticleFin;
        string strCompany;
        string strExcelFile;
        double Warpdensity = 1.0;
        double Weftdensity = 1.0;

        double WarpEnds = 1.0;
        double WeftEnds = 1.0;
        double Jdense = 0.0;
        double Wdense = 0.0;
        double TotalDense = 0.0;
        #endregion
        public GreigeMasterReport()
            : base()
        {
        }
        public GreigeMasterReport(Dictionary<string, object> dicParamater)
            : base(dicParamater)
        {
            ArticleNum = dicParamater["ArticleNum"].ToString().Trim();
            ArticleVar = dicParamater["ArticleVar"].ToString().Trim();
            ArticleColor = dicParamater["ArticleColor"].ToString().Trim();
            ArticleFin = dicParamater["ArticleFin"].ToString().Trim();
            strCompany = dicParamater["Company"].ToString().Trim();
            strExcelFile = dicParamater["ExcelFile"].ToString().Trim();
        }

        private void FillInSelvage(DataRow dwWASTKE)
        {

            Queue CellQueue = new Queue();
            string LRDes = "";
            string LDes = "";
            string RDes = "";
            string draftposition = "";
            string LeftSelvage = "";
            string RightSelvage = "";
            string SelvageSide = "L";
            LeftSelvage = dwWASTKE["WAKLLEIST"].ToString().Trim();
            RightSelvage = dwWASTKE["WAKRLEIST"].ToString().Trim();

            var query = (from dwWTLEIST in dsSource.Tables["WTLEIST"].AsEnumerable()
                         where dwWTLEIST.Field<string>("WTLLEIST").Trim() == LeftSelvage
                         select dwWTLEIST
                        ).Distinct();
            CellQueue.Clear();
            int Times = 0;
            foreach (DataRow dwQuery in query)
            {
                if (Times < 1)
                {
                    Times++;
                    CellQueue.Enqueue(SelvageSide + "EdgeName");
                    CellQueue.Enqueue("WTLLEIST");
                    CellQueue.Enqueue(SelvageSide + "EdgeDes");
                    CellQueue.Enqueue("WTLBEZ");
                    LDes = dwQuery["WTLBEZ"].ToString().Trim();
                    CellQueue.Enqueue(SelvageSide + "EdgeDraft");
                    CellQueue.Enqueue("WTLPASSNR");
                    CellQueue.Enqueue(SelvageSide + "EdgeWeave");
                    CellQueue.Enqueue("WTLBDG");
                    CellQueue.Enqueue(SelvageSide + "EdgeEnds");
                    CellQueue.Enqueue("WTLFDZ");
                    CellQueue.Enqueue(SelvageSide + "EdgeDent");
                    CellQueue.Enqueue("WTLEINZNR");
                    TotalSelvage += System.Convert.ToInt16(dwQuery["WTLFDZ"].ToString());

                    FillInCellbyQueue(CellQueue, dwQuery);
                }
            }
            SelvageSide = "R";
            query = (from dwWTLEIST in dsSource.Tables["WTLEIST"].AsEnumerable()
                     where dwWTLEIST.Field<string>("WTLLEIST").Trim() == RightSelvage
                     select dwWTLEIST).Distinct();
            CellQueue.Clear();
            Times = 0;
            foreach (DataRow dwQuery in query)
            {
                if (Times < 1)
                {
                    Times++;
                    CellQueue.Enqueue(SelvageSide + "EdgeName");
                    CellQueue.Enqueue("WTLLEIST");
                    CellQueue.Enqueue(SelvageSide + "EdgeDes");
                    CellQueue.Enqueue("WTLBEZ");
                    RDes = dwQuery["WTLBEZ"].ToString().Trim();
                    CellQueue.Enqueue(SelvageSide + "EdgeDraft");
                    CellQueue.Enqueue("WTLPASSNR");
                    CellQueue.Enqueue(SelvageSide + "EdgeWeave");
                    CellQueue.Enqueue("WTLBDG");
                    CellQueue.Enqueue(SelvageSide + "EdgeEnds");
                    CellQueue.Enqueue("WTLFDZ");
                    CellQueue.Enqueue(SelvageSide + "EdgeDent");
                    CellQueue.Enqueue("WTLEINZNR");
                    FillInCellbyQueue(CellQueue, dwQuery);
                    TotalSelvage += System.Convert.ToInt16(dwQuery["WTLFDZ"].ToString());
                }
            }
            LRDes = LDes + "+" + RDes;
            exAgent.SetCellValue("LRDes", LRDes, true);
            exAgent.SetCellValue("TotalSelvage", TotalSelvage, true);
        }
        private void FillInWeave(DataRow dwWASTAMM)
        {

            Queue CellQueue = new Queue();

            string Weave = "";
            string CellName = "Drafting";
            string ColumnName = "WATEXTE1";
            string CellValue = dwWASTAMM[ColumnName].ToString().Replace("  ", ""); ;
            exAgent.SetCellValue(CellName, CellValue, true);
            CellName = "WAFTCOMS";
            ColumnName = "WATEXTE2";
            CellValue = dwWASTAMM[ColumnName].ToString().Replace("  ", ""); ;
            exAgent.SetCellValue(CellName, CellValue, true);
            CellName = "LEdgeDraftCOMS";
            ColumnName = "WATEXTE3";
            CellValue = dwWASTAMM[ColumnName].ToString().Replace("  ", ""); ;
            exAgent.SetCellValue(CellName, CellValue, true);
            Weave = dwWASTAMM["WABIND"].ToString().Trim();
            CellQueue.Enqueue("WABIND");
            CellQueue.Enqueue("WABIND");
            FillInCellbyQueue(CellQueue, dwWASTAMM);
            string Client = "00";
            string Lang = "V";
            Weave = Weave + "                                       ";
            Weave = Client + Weave.Substring(0, 21) + Lang;
            var query = from dwWeave in dsSource.Tables["SDDAT"].AsEnumerable()
                        where dwWeave.Field<string>("SDSA") == "0109"
                        && dwWeave.Field<string>("SDKEY") == Weave
                        select dwWeave;
            CellQueue.Clear();
            foreach (DataRow dwQuery in query)
            {
                CellName = "WeaveDes";
                ColumnName = "SDDATEN";
                CellValue = GetGB2312Value(dwQuery[ColumnName].ToString().Substring(1, 40).Trim());
                exAgent.SetCellValue(CellName, CellValue, true);
                CellName = "WeaveCom";
                CellValue = dwQuery["COMMENTCN"].ToString().Replace("     ", "");
                exAgent.SetCellValue(CellName, CellValue, true);
            }
        }
        private void FillInFinish(DataTable dtFinish)
        {

            Queue CellQueue = new Queue();
            CellQueue.Clear();
            foreach (DataRow dwFinish in dtFinish.Rows)
            {
                CellQueue.Enqueue("FinishingDes");
                CellQueue.Enqueue("WAFBEZ");
                FillInCellbyQueue(CellQueue, dwFinish);
            }
        }
        private void FillInComposition(DataTable dtWASTAMM)
        {
            try
            {
                Queue CellQueue = new Queue();
                CellQueue.Clear();
                foreach (DataRow dwWASTAMM in dtWASTAMM.Rows)
                {
                    CellQueue.Enqueue("COMPOSITION");
                    CellQueue.Enqueue("ComCN");
                    FillInCellbyQueue(CellQueue, dwWASTAMM);
                    WANEUB = dwWASTAMM["WANEUB"].ToString().Trim();
                    WANEUD = dwWASTAMM["WANEUD"].ToString();
                    string aenb = dwWASTAMM["WANEUB"].ToString().Trim();
                    if (aenb != "")
                    {
                        if (aenb != WANEUB)
                        {
                            if (!WAAENB.Contains(aenb + ";"))
                            {
                                WAAENB += aenb + ";";
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void FillInWeaveColor(DataTable dtWAFARBEN)
        {
            try
            {

                Queue CellQueue = new Queue();
                foreach (DataRow dwWAFARBEN in dtWAFARBEN.Rows)
                {
                    CellQueue.Enqueue("WAFZUSATZ");
                    CellQueue.Enqueue("WAFZUSATZ");
                    CellQueue.Enqueue("WAFCOLORIT");
                    CellQueue.Enqueue("WAFZUSATZ");
                    CellQueue.Enqueue("COMS");
                    CellQueue.Enqueue("COMS");
                    FillInCellbyQueue(CellQueue, dwWAFARBEN);
                    string aenb = dwWAFARBEN["WAFAENDBEN"].ToString().Trim();
                    if (aenb != "")
                    {
                        if (aenb != WANEUB)
                        {
                            if (!WAAENB.Contains(aenb + ";"))
                            {
                                WAAENB += aenb + ";";
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void FillInWeftPattern(DataTable dtWTSCHUSS)
        {
            Dictionary<string, string> WeftMatrix = PatternMatrix(22, 40, true);
            Array WR = Array.CreateInstance(typeof(Int32), 4, 698);
            Array WM = Array.CreateInstance(typeof(Int32), 22, 698);
            string PatternS = "";
            string YarnEnds = "";
            Queue WRWRQueue = new Queue();
            Queue CellQueue = new Queue();
            CellQueue.Clear();
            foreach (DataRow dwWTSCHUSS in dtWTSCHUSS.Rows)
            {
                CellQueue.Enqueue("WeftPatternString");
                CellQueue.Enqueue("WTSBEZ");
                CellQueue.Enqueue("WPatternEnds");
                CellQueue.Enqueue("WTSSRAPP");
                WeftEnds = System.Convert.ToDouble(dwWTSCHUSS["WTSSRAPP"].ToString());
                FillInCellbyQueue(CellQueue, dwWTSCHUSS);
                string WTSANZFARB = dwWTSCHUSS["WTSANZFARB"].ToString();
                exAgent.SetCellValue(395, 34, WTSANZFARB);

                WRWRQueue.Enqueue(WR);
                WRWRQueue.Enqueue(WM);
                WRWRQueue = HandleWTSSCHUSS(WRWRQueue, dwWTSCHUSS, "F_P", "F_R");
                WR = (Array)WRWRQueue.Dequeue();
                WM = (Array)WRWRQueue.Dequeue();
            }
        }
        public string Byte2String(byte[] arrByte)
        {

            StringBuilder sb = new StringBuilder();

            foreach (byte b in arrByte)
            {

                sb.Append(b > 15 ? Convert.ToString(b, 16) : '0' + Convert.ToString(b, 16));

            }

            return sb.ToString();

        }
        public Queue HandleWTSSCHUSS(Queue WRWRQueue, DataRow dwWTSCHUSS, string PatternPre, string RepeatePre)
        {
            Array WR, WM;
            string CellName = "";
            string CellValue = "";
            string WTBTAB;
            string FieldName = "WTSSCHUSS01";
            b = (byte[])(dwWTSCHUSS[FieldName]);
            WTBTAB = Byte2String(b);
            FieldName = "WTSSCHUSS02";
            b = (byte[])(dwWTSCHUSS[FieldName]);
            WTBTAB += Byte2String(b);

            //WTBTAB = "0002001E0000000000000000000300270000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000";
            int ColStart = 0;
            WR = (Array)WRWRQueue.Dequeue();
            WM = (Array)WRWRQueue.Dequeue();
            string ColI = "";
            string WBi, WBj;
            int YarnI, EndsI, R1i, R2i, R3i, R4i;
            try
            {
                for (int i = 1; i <= 100; i++)
                {
                    //    "0002001E0000000000000000"
                    ColI = WTBTAB.Substring((i - 1) * 16, 16).ToUpper();
                    YarnI = System.Convert.ToInt16(ColI.Substring(0, 4), 16) - 1;
                    EndsI = Convert.ToInt32(ColI.Substring(4, 4), 16);
                    R1i = System.Convert.ToInt16(ColI.Substring(8, 4), 16);
                    WR.SetValue(R1i, 0, ColStart + i - 1);
                    R2i = System.Convert.ToInt16(ColI.Substring(12, 4), 16);
                    WR.SetValue(R2i, 1, ColStart + i - 1);
                    //EndsI = System.Convert.ToInt16(ColI.Substring(4, 4));

                    if (YarnI > -1)
                    {
                        WM.SetValue(EndsI, YarnI, ColStart + i - 1);
                    }
                }
                WRWRQueue.Enqueue(WR);
                WRWRQueue.Enqueue(WM);
                string PatternS = BuildPatternString(WR, WM, "WTSCHUSS");
                PatternS = PatternS.Replace("+", "");
                string PatternField = "WeftPatternString";
                CellName = PatternField;
                exAgent.SetCellValue(CellName, PatternS, true);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return WRWRQueue;
        }
        private Queue HandleWTBTAB(Queue WRWRQueue, string FieldName, DataRow dwWTSAER, string PatternPre, string RepeatePre)
        {
            Array WR, WM;
            string CellName = "";
            string CellValue = "";
            b = (byte[])(dwWTSAER[FieldName]);
            string WTBTAB = Byte2String(b);

            //WTBTAB = "0002001E0000000000000000000300270000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000";
            int ColStart = System.Convert.ToInt16(FieldName.Substring(6, 3)) - 1;
            int ColEnd = System.Convert.ToInt16(FieldName.Substring(9, 3)) - 1;
            WR = (Array)WRWRQueue.Dequeue();
            WM = (Array)WRWRQueue.Dequeue();
            string ColI = "";
            string WBi, WBj;
            int YarnI, EndsI, R1i, R2i, R3i, R4i;
            try
            {
                for (int i = 1; i <= 10; i++)
                {
                    //    "0002001E0000000000000000"
                    ColI = WTBTAB.Substring((i - 1) * 24, 24).ToUpper();
                    YarnI = System.Convert.ToInt16(ColI.Substring(0, 4), 16) - 1;
                    EndsI = Convert.ToInt32(ColI.Substring(4, 4), 16);
                    //EndsI = System.Convert.ToInt16(ColI.Substring(4, 4));

                    if (YarnI > -1)
                    {
                        WM.SetValue(EndsI, YarnI, ColStart + i - 1);

                        WBi = Right("00" + (YarnI + 1).ToString(), 2);
                        WBj = Right("000" + (ColStart + i).ToString(), 3);
                        CellName = PatternPre + WBi + WBj;
                        exAgent.SetCellValue(CellName, EndsI, true);
                    }

                    R1i = System.Convert.ToInt16(ColI.Substring(8, 4));
                    WR.SetValue(R1i, 0, ColStart + i - 1);

                    WBi = "01";
                    WBj = Right("000" + (ColStart + i).ToString(), 3);
                    CellName = RepeatePre + WBi + WBj;
                    if (R1i == 0)
                        CellValue = "";
                    else
                        CellValue = R1i.ToString();

                    exAgent.SetCellValue(CellName, CellValue, true);

                    R2i = System.Convert.ToInt16(ColI.Substring(12, 4));
                    WR.SetValue(R2i, 1, ColStart + i - 1);
                    WBi = "02";
                    WBj = Right("000" + (ColStart + i).ToString(), 3);
                    CellName = RepeatePre + WBi + WBj;
                    if (R2i == 0)
                        CellValue = "";
                    else
                        CellValue = R2i.ToString();

                    exAgent.SetCellValue(CellName, CellValue, true);

                    R3i = System.Convert.ToInt16(ColI.Substring(16, 4));
                    WR.SetValue(R3i, 2, ColStart + i - 1);
                    WBi = "03";
                    WBj = Right("000" + (ColStart + i).ToString(), 3);
                    CellName = RepeatePre + WBi + WBj;
                    if (R3i == 0)
                        CellValue = "";
                    else
                        CellValue = R3i.ToString();
                    exAgent.SetCellValue(CellName, CellValue, true);
                    R4i = System.Convert.ToInt16(ColI.Substring(20, 4));
                    WR.SetValue(R4i, 3, ColStart + i - 1);
                    WBi = "04";
                    WBj = Right("000" + (ColStart + i).ToString(), 3);
                    CellName = RepeatePre + WBi + WBj;
                    if (R4i == 0)
                        CellValue = "";
                    else
                        CellValue = R4i.ToString();
                    exAgent.SetCellValue(CellName, CellValue, true);
                }
                WRWRQueue.Enqueue(WR);
                WRWRQueue.Enqueue(WM);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return WRWRQueue;
        }

        private double ComputeDense(double TTLdensity, double TTLEnds, double YarnEnds, string Yarn)
        {
            double YarnDense = 0;
            double YarnCount = 0;

            var query = from dwGSDAT in dsSource.Tables["GSDAT"].AsEnumerable()
                        where dwGSDAT["GSART"].ToString().Trim() + "/" + dwGSDAT["GSVAR"].ToString().Trim() == Yarn
                        select dwGSDAT;

            foreach (DataRow dwYarn in query)
            {
                YarnCount = System.Convert.ToDouble(dwYarn["GSRECHNR"].ToString());
                YarnCount = System.Math.Sqrt(590.5 / YarnCount);
                YarnDense = 0.037 * TTLdensity * YarnEnds / TTLEnds * YarnCount;
            }
            return YarnDense;
        }
        private void FillInWeftYarn(string TgaType, DataTable dtWastga)
        {

            string Article;
            string Var;
            string Yarn;
            string YarnBase = "";
            #region WeftYarn
            var query = from dwWastga in dtWastga.AsEnumerable()
                        group dwWastga by new
                        {
                            YarnArticle = dwWastga["WAGGART"],
                            YarnVar = dwWastga["WAGGVAR"],
                            YarnColor = dwWastga["WAGGFARBE"],
                            YarnPos = dwWastga["WAGFOLGEPOS"]
                        }
                            into g
                            select new
                            {
                                Yarn = g.Key,
                                TtlBAGKGNET = g.Sum(dwWastga => dwWastga.Field<decimal>("WAGKGNET")),
                                TtlBAGKGBRUT = g.Sum(dwWastga => dwWastga.Field<decimal>("WAGKGBRUT")),
                                TtlEnds = g.Sum(dwWastga => dwWastga.Field<decimal>("WAGFDZ")),
                                MaxWastage = g.Max(dwWastga => dwWastga.Field<decimal>("WAGABF")),
                            };
            int YarnNum = 0;
            string YarnPosition = "";
            string YarnVardes = "";
            Queue CellQ = new Queue();
            foreach (var varYarn in query)
            {
                YarnNum++;
                YarnPosition = Right("00" + YarnNum.ToString(), 2);
                Article = varYarn.Yarn.YarnArticle.ToString();
                Var = varYarn.Yarn.YarnVar.ToString();
                Yarn = varYarn.Yarn.YarnArticle.ToString().Trim() + "/" + varYarn.Yarn.YarnVar.ToString().Trim() + "/" + varYarn.Yarn.YarnColor.ToString().Trim();
                Yarn = GetGB2312Value(Yarn);
                YarnBase = varYarn.Yarn.YarnArticle.ToString().Trim() + "/" + varYarn.Yarn.YarnVar.ToString().Trim();
                DataRow[] dwtemp = dsSource.Tables["GSDAT"].Select("GSART='" + Article + "' AND GSVAR='" + Var + "'");
                if (dwtemp.Count() > 0)
                {
                    DataRow dwt = dwtemp[0];
                    YarnVardes = GetGB2312Value(dwt["GSGARNBEZ"].ToString().TrimEnd());
                };
                CellQ.Enqueue("WWAGGART" + YarnPosition);
                CellQ.Enqueue(Yarn.ToString() + Environment.NewLine + YarnVardes);
                //CellQ.Enqueue(Yarn.ToString());
                CellQ.Enqueue("WAGGART" + YarnPosition);
                CellQ.Enqueue(Yarn.ToString());
                CellQ.Enqueue("WeftYarnDes" + YarnPosition);
                CellQ.Enqueue(GetYarnDes(dsSource.Tables["GSCOLOR"], Yarn));
                string TtlBAGKGNET = varYarn.TtlBAGKGNET.ToString();
                string TtlBAGKGBRUT = varYarn.TtlBAGKGBRUT.ToString();
                string TtlEnds = varYarn.TtlEnds.ToString();
                string MaxWastage = varYarn.MaxWastage.ToString();
                Wdense += ComputeDense(Weftdensity, WeftEnds, System.Convert.ToDouble(TtlEnds), YarnBase);
                CellQ.Enqueue("WAGKGBNET" + YarnPosition);
                CellQ.Enqueue(TtlBAGKGNET);
                CellQ.Enqueue("WAGKGBRUT" + YarnPosition);
                CellQ.Enqueue(TtlBAGKGBRUT);
                CellQ.Enqueue("WAGFDZ" + YarnPosition);
                CellQ.Enqueue(TtlEnds);
                CellQ.Enqueue("WAGABF" + YarnPosition);
                CellQ.Enqueue(MaxWastage);
            }
            FillInCellbyQueue(CellQ);
            string CellName = "";
            string Cellvalue = "";
            CellName = "Wdense";
            Cellvalue = Wdense.ToString();
            exAgent.SetCellValue(CellName, Cellvalue, true);
            #endregion
        }
        private void CheckDirectory(string root, string sub, string year)
        {
            try
            {
                string drlocal = root;
                string dr0 = "";

                #region========================LOCAL=====================
                drlocal = @"C:\intex.w\Report";
                if (!Directory.Exists(drlocal))
                    Directory.CreateDirectory(drlocal);
                #endregion
                drlocal = root;
                drlocal = Path.Combine(drlocal, sub);
                if (!Directory.Exists(drlocal))
                    Directory.CreateDirectory(drlocal);

                drlocal = Path.Combine(drlocal, year);
                if (!Directory.Exists(drlocal))
                    Directory.CreateDirectory(drlocal);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        public void CheckFTPDir(string root, string sub, string year)
        {
            string createdtimefile = PathHelper.ApplicationPath + "\\ftp.txt";
            string month = System.DateTime.Now.Month.ToString();
            string day = System.DateTime.Now.Day.ToString();
            string newfile = "/创建于" + year + month + day;
            try
            {
                string drlocal = root;
                if (!ftpClient.DirectoryExists(drlocal))
                {
                    ftpClient.CreateDirectory(drlocal);
                }
                drlocal = drlocal + "/" + sub;
                if (!ftpClient.DirectoryExists(drlocal))
                {
                    ftpClient.CreateDirectory(drlocal);
                }
                drlocal = drlocal + "/" + year;
                if (!ftpClient.DirectoryExists(drlocal))
                {
                    ftpClient.CreateDirectory(drlocal);
                    ftpClient.PutFile(createdtimefile, drlocal + newfile);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            finally
            {
                ftpClient.Open();
                ftpClient.Login();
            }
        }
        public override void WriteExcelReport(string fileType)
        {
            string tempfile = "";
            try
            {
                bool IsFTP = true;
                string root = "";
                string sub = "工艺单";
                string year = System.DateTime.Now.Year.ToString();
                root = Path.Combine(PathHelper.ApplicationPath, @"Report");
                CheckDirectory(root, sub, year);
                if (IsFTP)
                {
                    tempfile = FTPShareFile("工艺单", year, fileType);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            finally
            {
                if (File.Exists(tempfile))
                {
                    //File.Delete(tempfile);
                }
            }
        }
        public void FillInWEAVEPATTERN(DataSet setData)
        {
            DataSet setReturn = new DataSet();
            DataSet setResult = new DataSet();
            DataSet setWEAVE = new DataSet();
            INTEXDataSet setPATTERN = new INTEXDataSet();
            if (strCompany != "HWD")
                return;
            try
            {
                DataRow dwWASTAMM = setData.Tables["WASTAMM"].Rows[0];
                DataRow dwWASTPASS = setData.Tables["WASTPASS"].Rows[0];
                string PGAART = dwWASTAMM["WABIND"].ToString();
                string DFAART = dwWASTPASS["WSPPASS"].ToString();
                ARTICLEMASTERData m_AD = new ARTICLEMASTERData();
                setWEAVE = m_AD.LoadSetWEAVE();
                setResult = m_AD.QueryWeave(setWEAVE, PGAART, DFAART);
                setPATTERN.Merge(setResult);
                int rStart = 29;
                int cStart = 3;
                string pColumn = "";
                string value = "";
                var query = from DataRow dwTemp in setPATTERN.PEGPLAN.AsEnumerable()
                            orderby dwTemp["FN"]
                            descending
                            select dwTemp;
                foreach (DataRow dwTemp in query)
                {
                    rStart++;
                    cStart = 3;
                    for (int pi = 1; pi <= 16; pi++)
                    {
                        cStart++;
                        pColumn = "PG" + m_AD.Right("00" + pi.ToString(), 2);
                        if (dwTemp.Table.Columns.Contains(pColumn))
                        {
                            exAgent.SetCellValue(rStart, cStart, dwTemp[pColumn].ToString());
                        }
                    }
                }
                cStart = 23;
                rStart = 29;
                query = from DataRow dwTemp in setPATTERN.DRAFTING.AsEnumerable()
                        orderby dwTemp["FN"]
                        descending
                        select dwTemp;
                foreach (DataRow dwTemp in query)
                {
                    exAgent.SetCellValue(29, 24, dwTemp["DFADES"].ToString());
                    cStart++;
                    for (int pi = 1; pi <= 16; pi++)
                    {
                        pColumn = "D" + m_AD.Right("00" + pi.ToString(), 2);
                        if (dwTemp.Table.Columns.Contains(pColumn))
                        {
                            exAgent.SetCellValue(rStart + pi, cStart, dwTemp[pColumn].ToString());
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void HideNullRow()
        {
            try
            {
                int HidedRows = 0;
                int rowstart = 1;
                int rowend = 1;
                int col1, col2, col3;
                exAgent.HideRows(1, 1, 365, 1);
                return;
                var val1 = exAgent.GetCellValue(1, 1);
                var val2 = exAgent.GetCellValue(1, 1);
                var val3 = exAgent.GetCellValue(1, 1);
                //Case 1
                rowstart = 30; rowend = 51; col1 = 3;
                for (int Rowi = rowstart; Rowi <= rowend; Rowi++)
                {
                    val1 = exAgent.GetRangeValue(Rowi, Rowi, 9, 38);
                    if ((string)val1 == "0")
                    {
                        HidedRows++;
                        exAgent.HideRows(Rowi, col1, Rowi, col1);
                    }
                }
                rowstart = 53; rowend = 56; col1 = 2; col2 = 3;
                for (int Rowi = rowstart; Rowi <= rowend; Rowi++)
                {
                    val1 = exAgent.GetRangeValue(Rowi, Rowi, 9, 38);
                    if ((string)val1 == "0")

                        //.get_Value(Type.Missing);
                        if ((string)val1 == "0")
                        {
                            HidedRows++;
                            exAgent.HideRows(Rowi, col1, Rowi, col1);
                        }
                }
                rowstart = 341; rowend = 351; col1 = 17; col2 = 23;
                for (int Rowi = rowstart; Rowi <= rowend; Rowi++)
                {
                    val1 = exAgent.GetRangeValue(Rowi, Rowi, 3, 4);
                    val2 = exAgent.GetRangeValue(Rowi, Rowi, 21, 22);
                    if ((string)val1 == "0" && (string)val2 == "0")
                    {
                        HidedRows++;
                        exAgent.HideRows(Rowi, col1, Rowi, col2);
                    }
                }
                int InsertedRows = HidedRows - 22;
                if (HidedRows > 0)
                {
                    rowstart = 359;
                    exAgent.InsertRows(rowstart, HidedRows - 22);
                }
                rowstart = 433 + InsertedRows; rowend = 1800 + InsertedRows;
                for (int Rowi = rowstart; Rowi <= rowend; Rowi++)
                {
                    val1 = exAgent.GetRangeValue(Rowi, Rowi, 8, 34);
                    if ((string)val1 == "0")
                    {
                        if (Rowi == rowstart)
                            Rowi = Rowi - 1;
                        exAgent.HideRows(Rowi, col1, rowend, col1);
                        Rowi = rowend;
                    }
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void HideNullRow(string Company = "HWD")
        {
            try
            {
                int HidedRows = 0;
                int rowstart = 1;
                int rowend = 1;
                int col1, col2, col3;

                var val1 = exAgent.GetCellValue(1, 1);
                var val2 = exAgent.GetCellValue(1, 1);
                var val3 = exAgent.GetCellValue(1, 1);
                //Case 1
                /*
                rowstart = 34; rowend = 55; col1 = 3;
                for (int Rowi = rowstart; Rowi <= rowend; Rowi++)
                {
                    val1 = exAgent.GetRangeValue(Rowi, Rowi, 9, 38);
                    if ((string)val1 == "0")
                    {
                        HidedRows++;
                        exAgent.HideRows(Rowi, col1, Rowi, col1);
                    }
                }
                rowstart = 57; rowend = 60; col1 = 2; col2 = 3;
                */
                rowstart = 34; rowend = 352; col1 = 2; col2 = 3;

                for (int Rowi = rowstart; Rowi <= rowend; Rowi++)
                {
                    val1 = exAgent.GetRangeValue(Rowi, Rowi, 9, 38);
                    if ((string)val1 == "0")

                        //.get_Value(Type.Missing);
                        if ((string)val1 == "0")
                        {
                            HidedRows++;
                            exAgent.HideRows(Rowi, col1, Rowi, col1);
                        }
                }
                rowstart = 355; rowend = 365; col1 = 17; col2 = 23;
                for (int Rowi = rowstart; Rowi <= rowend; Rowi++)
                {
                    val1 = exAgent.GetRangeValue(Rowi, Rowi, 3, 4);
                    val2 = exAgent.GetRangeValue(Rowi, Rowi, 34, 35);
                    if ((string)val1 == "0" && (string)val2 == "0")
                    {
                        HidedRows++;
                        exAgent.HideRows(Rowi, col1, Rowi, col2);
                    }
                }
                int InsertedRows = 0;
                /*
                InsertedRows = HidedRows - 18;
                if (HidedRows > 0)
                {
                    rowstart = 380;
                    exAgent.InsertRows(rowstart, HidedRows - 18);
                }
                */
                rowstart = 400 + InsertedRows; rowend = 1800 + InsertedRows;
                for (int Rowi = rowstart; Rowi <= rowend; Rowi++)
                {
                    val1 = exAgent.GetRangeValue(Rowi, Rowi, 8, 34);
                    if ((string)val1 == "0")
                    {
                        if (Rowi == rowstart)
                            Rowi = Rowi - 1;
                        exAgent.HideRows(Rowi, col1, rowend, col1);
                        Rowi = rowend;
                    }
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void FillInExcelData(string sheetName)
        {
            string CellName = "";
            string TableName = "";
            bool MultiRow = false;
            bool PatternTable;
            int Rown = 0;
            string sRow = "";
            Queue CellQueue = new Queue();
            string value = "";
            Dictionary<string, string> WarpMatrix = PatternMatrix(9, 40, true);
            Array WR = Array.CreateInstance(typeof(Int32), 4, 30);
            Array WM = Array.CreateInstance(typeof(Int32), 9, 30);
            CellName = "PrintDate";
            value = System.DateTime.Today.ToShortDateString();
            exAgent.SetCellValue(CellName, value, true);
            if (dsSource.Tables["WASTAMM"].Rows.Count == 0)
                return;
            DataRow dwWASTAMM = dsSource.Tables["WASTAMM"].Rows[0];
            //exAgent.HiddenWorkSheet(sheetName);
            Warpdensity = System.Convert.ToDouble(dwWASTAMM["WARFDDIK"].ToString());
            Warpdensity = Warpdensity / 2.54 * 10;
            Weftdensity = System.Convert.ToDouble(dwWASTAMM["WARFDDIS"].ToString());
            Weftdensity = Weftdensity / 2.54 * 10;
            string FEnlongation = dwWASTAMM["FEnlongation"].ToString();
            exAgent.SetCellValue(373, 11, FEnlongation, false);
            #region BySequence
            FillInFinish(dsSource.Tables["WAFINISH"]);
            FillInWeaveColor(dsSource.Tables["WAFARBEN"]);
            FillInComposition(dsSource.Tables["WASTAMM"]);
            FillInWeftPattern(dsSource.Tables["WTSCHUSS"]);

            if (dsSource.Tables["WASTKE"].Rows.Count > 0)
            {
                FillInWarpBeam("WS31", dsSource.Tables["WASTKE"].Rows[0]);
                FillInSelvage(dsSource.Tables["WASTKE"].Rows[0]);
                TotalEnds = WarpBeamEnds11 + TotalSelvage;
                CellName = "TotalEnds";
                exAgent.SetCellValue(CellName, TotalEnds, true);
            }
            else
            {
                Tracer.Verbose("", "WS31 设定错误");
            }
            FillInWarpYarn("BS08", dsSource.Tables["BASTGA"]);
            FillInWarpYarn("WS31", dsSource.Tables["BASTGA"]);
            FillInWeftYarn("WS33", dsSource.Tables["WASTGA"]);
            TotalDense = Jdense + Wdense - (Jdense * Wdense / 100);
            CellName = "TotalDense";
            exAgent.SetCellValue(CellName, TotalDense, true);
            FillInWEAVEPATTERN(dsSource);
            #endregion
            #region DataTable
            foreach (DataTable dtArticle in dsSource.Tables)
            {
                TableName = dtArticle.TableName;


                if (TableName == "ARTICLE" || TableName == "ARTICLECOLOR" || TableName == "ARTICLEVAR"
                    || TableName == "ARTICLEFINISH" || TableName == "Pattern")
                {
                    continue;
                }
                MultiRow = false;
                PatternTable = false;
                Rown = 0;
                if (MultiRowTable.Contains(TableName + ";"))
                {
                    MultiRow = true;
                }
                if (PatternTables.Contains(TableName + ";"))
                {
                    PatternTable = true;
                }

                if (TableName == "WTSCHUSS"
                    || TableName == "WAFINISH"
                    || TableName == "BASTGA"
                    || TableName == "WASTGA"
                    || TableName == "WASTKE"
                    || TableName == "WAFARBEN"
                    )
                {
                    continue;
                }
                #region DataRow
                foreach (DataRow dwArticle in dtArticle.Rows)
                {
                    Rown++;

                    if (TableName == "WASTPASS")
                    {
                        FillInDrafting(dwArticle);
                        continue;
                    }
                    if (TableName == "WASTAMM")
                    {
                        FillInWeave(dwArticle);
                    }
                    #region DataColumn
                    foreach (DataColumn dc in dwArticle.Table.Columns)
                    {
                        CellName = dc.ColumnName;
                        if (MultiRow)
                        {
                            sRow = "00" + Rown.ToString();
                            sRow = Right(sRow, 2);
                            CellName = CellName + sRow;
                        }
                        //exAgent.SetCellValue(CellName, value, true);
                        CellQueue.Enqueue(CellName);
                        CellQueue.Enqueue(dc.ColumnName);
                        FillInCellbyQueue(CellQueue, dwArticle);
                    }
                }
                    #endregion
                #endregion
            #endregion
            }

            //exAgent.SetCellValue(409,4,WANEUB);
            //exAgent.SetCellValue(409,7,WANEUD);
            //exAgent.SetCellValue(409,30,WAAENB);
            //设计:			FPDE			20110703											改进:		WLPEI;			
            //WAAENB = m_GM.Left(WAAENB + "________________________", 20);
            //exAgent.WorkSheet.PageSetup.LeftFooter = "设计:	" + WANEUB + "  " + WANEUD;
            //exAgent.WorkSheet.PageSetup.RightFooter = "改进:	" + WAAENB;
            string format = (string)dicOrigion["FORMAT"];
            switch (format)
            {
                case "中样试制":
                    exAgent.WorkSheet.PageSetup.CenterHeader = "&\"黑体\"&22" + "中样试制工艺卡";
                    exAgent.WorkSheet.PageSetup.RightHeader = "HL-EM-B-06            ";
                    //exAgent.SetCellValue(369, 25, "中样");
                    break;
                case "产品工艺":
                default:
                    //exAgent.SetCellValue(369, 25, "大货");
                    exAgent.WorkSheet.PageSetup.CenterHeader = "&\"黑体\"&22" + "产品工艺卡";
                    exAgent.WorkSheet.PageSetup.RightHeader = "HL-EM-B-12            ";
                    break;

            }
            if (exAgent != null)
            {
                if (strCompany == "HLT")
                {
                    HideNullRow();
                }
                else
                {
                    HideNullRow(strCompany);
                }
            }
        }
        private string CreateFile(string sheetname, string year, string localexcel)
        {
            string filename = "";
            try
            {
                string pwd = "intex4htl";
                string Standard = "Standard";
                strExcelFile = @"HLT\HLTStandard.xls";
                string filePath = @"C:\intex.w\Report\HLT\HLTStandard.xls";
                sheetname = m_GM.Convert8859P1ToGB2312(ArticleNum + "_" + ArticleVar + "_" + ArticleColor + "_" + ArticleFin);
                exAgent.Open(filePath);
                exAgent.Company = strCompany;
                exAgent.strExcelFile = strExcelFile;
                string wbname = "工艺单\\" + year + "\\" + ArticleNum + ".xls";
                string oldfile = exAgent.FileName.Replace(strExcelFile, wbname);
                if (System.IO.File.Exists(oldfile))
                {
                    System.IO.File.Delete(oldfile);
                }
                exAgent.CreateNewSheet(wbname, Standard, sheetname, pwd, localexcel);
                filename = exAgent.FileName;

                exAgent.SetCurrentSheet(1);
                FillInExcelData(sheetname);
                exAgent.Save();
                exAgent.Close();
                if (filename != oldfile)
                {
                    System.IO.File.Copy(filename, oldfile, true);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return filename;
        }
        private string FTPShareFile(string sub, string year, string fileType)
        {
            string localFile = "";
            string tempfile = "";
            string root = "/Technical/";
            try
            {
                /*
                ftpClient.Open();
                ftpClient.Login();              
                ftpClient.SetCurrentDirectory("/");
                CheckFTPDir("/Technical", "Temp", year);
                ftpClient.SetCurrentDirectory("/");
                CheckFTPDir("/Technical", "Backup", year);
                ftpClient.SetCurrentDirectory("/");
                string destfile;
                filename = root + "Temp/" + year + "/" + ArticleNum + ".xls"; ;
                  destfile = filename;
                 */
                #region==========产生文件，复制到服务器=======================

                /*if (ftpClient.FileExists(filename))
                {
                    localFile = @"C:\Windows\Temp\" + ArticleNum + ".xls";
                    ftpClient.GetFile(filename, localFile, false);
                    ftpClient.RemoveFile(filename);
                }*/
                tempfile = CreateFile(ArticleNum, year, localFile);
                localFile = tempfile;
                //ftpClient.PutFile(tempfile, destfile);

                #endregion
                #region=========打开服务器上的文件进行浏览========================

                if (fileType == "OpenExcel")
                {
                    /*
                    localFile = @"C:\Windows\Temp\" + ArticleNum + ".xls";

                    if (System.IO.File.Exists(localFile))
                    {
                        System.IO.File.Delete(localFile);
                    }
                    ftpClient.GetFile(filename, localFile, false);
                     */
                    System.Diagnostics.Process.Start("EXCEL.EXE", localFile);
                    //System.Threading.Thread.Sleep(2000);
                }
                #endregion
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            finally
            {

            }
            return localFile;
        }
    }
}
